package cn.com.guage.transtation;

import java.util.ArrayList;
import java.util.List;

// 资源管理器接口
interface ResourceManager {
    boolean prepare();

    void commit();

    void rollback();
}

// 具体资源管理器实现
class ZhangSanBankAccountRM implements ResourceManager {
    private String accountId;
    private double balance;

    public ZhangSanBankAccountRM(String accountId, double balance) {
        this.accountId = accountId;
        this.balance = balance;
    }

    @Override
    public boolean prepare() {
        System.out.println("Account " + accountId + " is preparing... 张三扣款1000元-----张三扣款事务未提交");
        return true;
    }

    @Override
    public void commit() {
        System.out.println("Account " + accountId + " is committed.  张三扣款事务提交");
    }

    @Override
    public void rollback() {
        System.out.println("Account " + accountId + " is rolled back.");
    }
}

// 具体资源管理器实现
class LiSiBankAccountRM implements ResourceManager {
    private String accountId;
    private double balance;

    public LiSiBankAccountRM(String accountId, double balance) {
        this.accountId = accountId;
        this.balance = balance;
    }

    @Override
    public boolean prepare() {
        System.out.println("Account " + accountId + " is preparing... 李四入账1000元-----李四入账事务未提交");
        return true;
    }

    @Override
    public void commit() {
        System.out.println("Account " + accountId + " is committed.  李四入账事务提交");
    }

    @Override
    public void rollback() {
        System.out.println("Account " + accountId + " is rolled back.");
    }
}


// 事务管理器
class TransactionManager {
    private List<ResourceManager> resourceManagers = new ArrayList<>();

    public void addResourceManager(ResourceManager rm) {
        resourceManagers.add(rm);
    }

    public void twoPhaseCommit() {
        // 准备阶段
        boolean allPrepared = true;
        for (ResourceManager rm : resourceManagers) {
            if (!rm.prepare()) {
                allPrepared = false;
                break;
            }
        }

        // 提交阶段
        if (allPrepared) {
            for (ResourceManager rm : resourceManagers) {
                rm.commit();
            }
        } else {
            for (ResourceManager rm : resourceManagers) {
                rm.rollback();
            }
        }
    }
}

// 测试代码
public class TwoPhaseCommitExample {
    public static void main(String[] args) {
        TransactionManager tm = new TransactionManager();
        ZhangSanBankAccountRM rm1 = new ZhangSanBankAccountRM("A001", 1000);
        LiSiBankAccountRM rm2 = new LiSiBankAccountRM("A002", 2000);
        tm.addResourceManager(rm1);
        tm.addResourceManager(rm2);
        tm.twoPhaseCommit();
    }
}